const defaultConfig = (options) => {
  const { header, timeout } = options
  if (!header) {
    options.header = {
      "content-type": "application/json"
    }
  }
  if (!timeout) {
    options.timeout = 300000 // 请求过期时间
  }
  return options
}
const request = options => {
  return new Promise((resolve, reject) => {
    wx.request({
      ...options,
      success(res) {
        console.log(res)
        const data = res.data
        const code = res.data.code
        //  if(code === 100002){ // 超时
        //    reject(res.data)
        //  }
        if (code === 0 || code === 200) {
          resolve(data)
        } else {
          reject(data)
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
const downloadFile = options => {
  defaultConfig(options)
  return new Promise((resolve, reject) => {
    wx.downloadFile({
      ...options,
      success(res) {
        const data = res.data
        const code = data.code
        if (code === 0) {
          resolve(data)
        } else {
          console.log(data)
          reject(data)
        }
      },
      fail(err) {
        console.log(err)
        reject(err)
      }
    })
  })
}
const uploadFile = options => {
  defaultConfig(options)
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      ...options,
      success(res) {
        const data = res.data
        const code = data.code
        if (code === 0) {
          resolve(data)
        } else {
          reject(data)
        }
      },
      fail(err) {
        reject(err)
      }
    })
  })
}
const post = (options) => {
  const { data } = options
  defaultConfig(options)
  options.data = JSON.stringify(data)
  options.method = 'post'
  return request(options)
}
const get = (options) => {
  defaultConfig(options)
  options.method = 'get'
  return request(options)
}
const del = (options) => {
  defaultConfig(options)
  options.method = 'delete'
  return request(options)
}
const put = (options) => {
  defaultConfig(options)
  options.method = 'put'
  return request(options)
}
module.exports = {
  post,
  get,
  del,
  put,
  downloadFile,
  uploadFile
}